///:SessionFactory.java
package cn.weyoungstudio.hwes.jdbc.session;

import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;

import javax.sql.DataSource;
import java.io.Closeable;
import java.io.IOException;

/**
 * @author icechen1219
 * @date 2020/05/22
 */
public class SqlSessionFactory {
    private static DataSource dataSource;
    private static boolean autoCommit;
    private volatile static SqlSessionFactory sqlSessionFactory;

    private SqlSessionFactory() {
        String configFile = "src/main/resources/db.properties";

        HikariConfig cfg = new HikariConfig(configFile);
        dataSource = new HikariDataSource(cfg);
        autoCommit = Boolean.parseBoolean(cfg.getDataSourceProperties().getProperty("dataSource.autoCommit"));
    }

    public static SqlSessionFactory createSqlSessionFactory() {
        if (sqlSessionFactory == null) {
            synchronized (SqlSessionFactory.class) {
                if (null == sqlSessionFactory) {
                    sqlSessionFactory = new SqlSessionFactory();
                }
            }
        }
        return sqlSessionFactory;
    }

    public SqlSession openSession() {
        return new SqlSessionImpl(dataSource, autoCommit);
    }

    public void close() {
        try {
            ((Closeable) dataSource).close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
///:SessionFactory.java
